//
//  GJFMineViewController.m
//  Wedding
//
//  Created by 郭静芬 on 2016/12/20.
//  Copyright © 2016年 郭静芬. All rights reserved.
//

#import "GJFMineViewController.h"
#import "GJFMineModel.h"
#import "GJFMineHeaderView.h"
#import "GJFEditPersonViewController.h"
#import "GJFCollecionViewController.h"
#import "GJFEditSignBackViewController.h"
#import "GJFWebViewController.h"
#import "GJFRegisterViewController.h"

@interface GJFMineViewController () <UITableViewDelegate, UITableViewDataSource, GJFMineHeaderViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<GJFMineModel *> *> *mineArray;
@property (nonatomic, strong) GJFMineHeaderView *headerView;
@property (nonatomic, copy) NSString *cacheSize;
@end

@implementation GJFMineViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self floatWithPath];
    [self getPersonalData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mineArray = [NSMutableArray array];
    NSString *mineString = [[NSBundle mainBundle] pathForResource:@"MineList" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:mineString];
    [self.mineArray addObject:[GJFMineModel transformWithArr:dict[@"section_0"]]];
    [self.mineArray addObject:[GJFMineModel transformWithArr:dict[@"section_1"]]];
    [self.mineArray addObject:[GJFMineModel transformWithArr:dict[@"section_2"]]];
    [self.headerView reloadData];
    [self tableView];
}
// 用户信息网络请求
- (void)getPersonalData {
    [GJFNetworkTool POSTRequestWithUrl:APP_MINE_INFO params:@{} complete:^(NSDictionary *result) {
        if ([result[@"code"] intValue] == 1000) {
            // 获取信息并保存到本地
            GJFSingleTool *single = [GJFSingleTool shareInstance];
            single.userInfo = [GJFUserInfo mj_objectWithKeyValues:result[@"data"]];
            [GJFSingleTool saveUserInfo];
            [self.headerView reloadData];
        }
    }];
}

#pragma mark - TableView的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([GJFSingleTool is_login]) {
        return self.mineArray.count;
    }
    else {
        return self.mineArray.count - 1;
    }
}
#pragma mark - TableView每个分区中row数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.mineArray[section] count];
}
#pragma mark - TableView每个分区中row的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"MineCell"];
    }
    cell.textLabel.text = [self.mineArray[indexPath.section][indexPath.row] title];
    cell.imageView.image = [UIImage imageNamed:[self.mineArray[indexPath.section][indexPath.row] image]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section > 0 && indexPath.row == 0) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        if (indexPath.section == 1) {
            cell.detailTextLabel.text = [GJFSingleTool app_version];
        }
    }
    else {
        if (indexPath.section == 0 && indexPath.row == 0) {
            cell.detailTextLabel.text = self.cacheSize;
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

#pragma mark - TableView每个分区中cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45 * YY;
}
#pragma mark - TableView每个分区头部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 30 * YY;
    }
    else {
        return 10 * YY;
    }
}
#pragma mark - TableView每个分区尾部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == self.mineArray.count - 1) {
        return 30 * YY;
    }
    return 0.01;
}
// 去除cell底部横线左侧间距
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.separatorInset = UIEdgeInsetsZero;
}

#pragma mark - TableView的跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        // 清除缓存
        [self removeCache];
    }
    else if (indexPath.section == 0 && indexPath.row == 1) {
        // 收藏
        if ([GJFSingleTool is_login]) {
            GJFCollecionViewController *collectVC = [[GJFCollecionViewController alloc] init];
            collectVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:collectVC animated:YES];
        }
        else {
            [self skipLoginVc];
        }
    }
    else if (indexPath.section == 1 && indexPath.row == 1) {
        GJFEditSignBackViewController *feedbackVC = [[GJFEditSignBackViewController alloc] init];
        feedbackVC.hidesBottomBarWhenPushed = YES;
        feedbackVC.editPersonMineStyle = EditMineFeedback;
        [self.navigationController pushViewController:feedbackVC animated:YES];
    }
    else if (indexPath.section == 1 && indexPath.row == 2) {
        GJFWebViewController *aboutMineVC = [[GJFWebViewController alloc] init];
        aboutMineVC.hidesBottomBarWhenPushed = YES;
        NSString *url = [[[GJFSingleTool shareInstance] userInfo] about_mine] ? :@"https://www.baidu.com/";
        [aboutMineVC createInfoWithTitle:@"关于我们" url:url options:nil];
        [self.navigationController pushViewController:aboutMineVC animated:YES];
    }
    else if (indexPath.section == 2){
        // 退出登录
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要退出登录吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alertController addAction:cancelAction];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self logout];
        }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:^{}];
    }
}

- (void)logout {
    GJFUserInfo *userInfo = [GJFSingleTool shareInstance].userInfo;
    userInfo.token = nil;
    userInfo.avatar = nil;
    [GJFSingleTool saveUserInfo];
    [self.tableView reloadData];
    [self.headerView reloadData];
}

#pragma mark - 缓存计算
// 计算清除的缓存大小
- (void)floatWithPath {
    // 获取cache路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"default"];
    CGFloat num = 0;
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:path]) {
        NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];
        NSString *fileName;
        while ((fileName = [childFile nextObject]) != nil) {
            NSString *fileSub = [path stringByAppendingPathComponent:fileName];
            num += [self fileSizeAtPath:fileSub];
        }
    }
    self.cacheSize = [NSString stringWithFormat:@"%.0f M", ceil(num / (1024 * 1024))];
    [self.tableView reloadData];
}
//计算单个文件大小
- (long long)fileSizeAtPath:(NSString *)file
{
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:file]) {
        return [[man attributesOfItemAtPath:file error:nil] fileSize];
    }
    return 0;
}

#pragma mark - 删除缓存
- (void)removeCache
{
    NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"default"];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *p in files) {
        NSString * path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
    }
    self.cacheSize = @"0 M";
    [self.view showWarning:@"清除成功"];
    [self.tableView reloadData];
}

#pragma mark - TableView头部的协议方法
- (void)skipEditPerson {
    if ([GJFSingleTool is_login]) {
        GJFEditPersonViewController *editPerVC = [[GJFEditPersonViewController alloc] init];
        editPerVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:editPerVC animated:YES];
    }
    else {
        [self skipLoginVc];
    }
}

#pragma mark - 去登录
- (void)skipLoginVc {
    GJFRegisterViewController *registerVC = [[GJFRegisterViewController alloc] init];
    registerVC.hidesBottomBarWhenPushed = YES;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:registerVC];
    [self presentViewController:nav animated:YES completion:^{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    }];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49 - 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = self.headerView;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (GJFMineHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[GJFMineHeaderView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 240 * YY)];
        _headerView.delegate = self;
        _headerView.backgroundColor = [UIColor whiteColor];
        
    }
    return _headerView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
